import { defineStore } from "pinia";
import { constantRoutes, asyncRouters } from "@/router/routeMap.ts";

// 通过route.meta.roles判断是否与当前roles匹配
const hasPermission = (roles, route) => {
    if (route.meta && route.meta.roles) {
        return roles.some((role) => route.meta.roles.includes(role));
    } else {
        return true;
    }
};

// 递归遍历路由，把有权限的路由遍历出来
const filterAsyncRoutes = (routes, roles) => {
    const res = [];
    routes.forEach((route) => {
        const tmp = { ...route };
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles);
            }
            res.push(tmp);
        }
    });
    return res;
};

export const usePermissionStore = defineStore("permissionStore", {
    state: () => {
        return {
            routes: [],
            addRoutes: [],
        };
    },
    getters: {},
    actions: {
        setRoutes(addRoutes: []) {
            this.addRoutes = addRoutes;
            this.routes = constantRoutes.concat(addRoutes);
        },
        generateRoutes(roles: []) {
            const _this = this;
            return new Promise((resolve) => {
                const accessedRoutes = filterAsyncRoutes(asyncRouters, roles); // 过滤出有权限的路由
                _this.setRoutes(accessedRoutes); // 把有权限的路由塞到pinia中
                resolve(accessedRoutes);
            });
        },
    },
    persist: true,
});
export default usePermissionStore;
